package com.stylefeng.guns.core.util;

import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.exception.ServiceExceptionEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.stream.Stream;

/**
 *
 * @Description: 文件上传处理工具类
 *
 * @Author: zhusheng
 * @Date: Created in 2018/5/14 11:44
 * @ModifyBy:
 */
public class WebFileUtil {

    /**
     * 上传文件
     * @param file 上传的文件对象
     * @param dir 上传目录
     * @param  isImage 上传的是否是图片
     * @param  saveFileName 保存的文件名称
     * @return String 返回文件名称有后缀
     * @throws RuntimeException
     */
    public static String upload(MultipartFile file, String dir, boolean isImage, String saveFileName) throws RuntimeException {
        if (file.isEmpty()) {
            throw new GunsException(UploadExceptionEnum.UPLOAD_FILE_EMPTY);
        }

        if(StringUtils.isEmpty(dir)){
            throw new RuntimeException("文件存放目录为空");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);

        if(isImage && !isImage(suffixName)){
            throw new GunsException(UploadExceptionEnum.UPLOAD_FILE_NOT_IMAGE);
        }

        String finalFileName = UUID.randomUUID().toString() + "." + suffixName;


        if(StringUtils.isNotEmpty(saveFileName)){
            finalFileName = saveFileName  + "." + suffixName ;
        }
        // 解决中文问题，liunx下中文路径，图片显示问题
        String finalPath = dir + File.separator +finalFileName;

        File dest = new File(finalPath);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
        }catch (IOException e){
            throw new RuntimeException(e);
        }

        return finalFileName;
    }

    /**
     * 上传文件
     * @param file 上传的文件对象
     * @param dir 文件目录
     * @return
     * @throws RuntimeException
     */
    public static String uploadFile(MultipartFile file, String dir) throws RuntimeException {
        if (file.isEmpty()) {
            throw new GunsException(UploadExceptionEnum.UPLOAD_FILE_EMPTY);
        }
        if(StringUtils.isEmpty(dir)){
            throw new RuntimeException("文件存放目录为空");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String finalFileName = UUID.randomUUID().toString() + "." + suffixName;
        // 解决中文问题，liunx下中文路径，图片显示问题
        // 将文件后缀作为文件夹
        String finalPath = dir + File.separator + suffixName + File.separator +finalFileName;
        File dest = new File(finalPath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        return finalFileName;
    }

    /**
     * 是否是图片
     * @param suffixName String 文件后缀名
     * @return boolean
     */
    public static boolean isImage(String suffixName){

        return Stream.of("BMP","JPG","JPEG","PNG","GIF","BMP","PCX","TIFF","TGA","EXIF"
                ,"FPX","SVG","PSD","CDR","PCD","DXF","UFO","EPS","HDRI","AI","RAW")
                .filter(str -> str.equals(suffixName.toUpperCase()))
                .findAny()
                .isPresent();
    }

    /**
     * 上传图片
     * @param file
     * @param dir
     * @return
     * @throws RuntimeException
     * @throws IOException
     */
    public static String uploadImage(MultipartFile file, String dir) throws RuntimeException {
        return upload(file, dir, true,null);
    }

    /**
     * 上传图片
     * @param file
     * @param dir
     * @return
     * @throws RuntimeException
     * @throws IOException
     */
    public static String uploadImageDefineName(MultipartFile file, String dir, String saveFileName) throws RuntimeException {
        return upload(file, dir, true, saveFileName);
    }


    /**
     * 上传异常信息枚举类
     */
    private enum  UploadExceptionEnum implements ServiceExceptionEnum {

        UPLOAD_FILE_EMPTY(501,"上传文件为空"),
        UPLOAD_FILE_NOT_IMAGE(502,"文件格式不是图片");

        UploadExceptionEnum(int code, String message) {
            this.code = code;
            this.message = message;
        }

        private Integer code;

        private String message;

        @Override
        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        @Override
        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

}
